import { ref, computed, watch } from 'vue'
import type { PropertyPanelProps } from '../types'
import Modeling from 'bpmn-js/lib/features/modeling/Modeling.js'
import type { Moddle } from 'bpmn-moddle'
import { ApproveMethodType, APPROVE_METHODS } from '../const/const'

export interface MultiInstanceConfig {
  isSequential: boolean // true: 依次审批, false: 会签
  completionCondition: string // 完成条件
  loopCardinality: string // 循环基数（会签人数）
  collection: string // 集合表达式
  approveMethod: ApproveMethodType // 审批方式
  approveRatio: number // 会签通过比例（百分比）
}

export function useMultiInstanceConfig(props: PropertyPanelProps) {
  // 是否开启会签
  const isMultiInstance = ref(false)

  // 会签配置
  const multiInstanceConfig = ref<MultiInstanceConfig>({
    isSequential: false,
    completionCondition: '${ nrOfCompletedInstances >= nrOfInstances }',
    loopCardinality: '1',
    collection: '${coll_userList}',
    approveMethod: ApproveMethodType.SEQUENTIAL_APPROVE,
    approveRatio: 100,
  })

  // 会签流程变量说明
  const multiInstanceVariables = [
    { name: 'nrOfInstances', desc: '会签总数' },
    { name: 'nrOfCompletedInstances', desc: '已完成的会签数量' },
    { name: 'nrOfActiveInstances', desc: '当前活动的会签数量' },
    { name: 'loopCounter', desc: '当前会签的索引（从0开始）' },
  ]

  // 是否显示会签配置
  const showMultiInstance = computed(() => {
    if (!props.currentElement) return false
    return props.currentElement.type === 'bpmn:UserTask'
  })

  // 监听元素变化，同步会签状态
  watch(
    () => props.currentElement,
    (element) => {
      if (!element) return
      const loopCharacteristics = element.businessObject.loopCharacteristics
      // 更新会签开关状态
      isMultiInstance.value = !!loopCharacteristics

      if (loopCharacteristics) {
        // 从完成条件中提取审批比例
        let approveRatio = 100
        const completionCondition = loopCharacteristics.completionCondition?.body || ''
        const ratioMatch = completionCondition.match(
          /nrOfCompletedInstances\/nrOfInstances\s*>=\s*([0-9.]+)/,
        )
        if (ratioMatch && ratioMatch[1]) {
          approveRatio = Math.round(parseFloat(ratioMatch[1]) * 100)
        }

        // 根据特征判断审批方式
        let approveMethod = ApproveMethodType.SEQUENTIAL_APPROVE
        if (loopCharacteristics.isSequential) {
          approveMethod = ApproveMethodType.SEQUENTIAL_APPROVE
        } else if (completionCondition.includes('nrOfCompletedInstances/nrOfInstances')) {
          approveMethod = ApproveMethodType.APPROVE_BY_RATIO
        } else if (completionCondition.includes('nrOfCompletedInstances >= 1')) {
          approveMethod = ApproveMethodType.ANY_APPROVE
        } else if (
          !loopCharacteristics.isSequential &&
          loopCharacteristics.loopCardinality?.body === '1'
        ) {
          approveMethod = ApproveMethodType.RANDOM_SELECT_ONE_APPROVE
        }

        multiInstanceConfig.value = {
          isSequential: loopCharacteristics.isSequential || false,
          completionCondition:
            loopCharacteristics.completionCondition?.body ||
            '${ nrOfCompletedInstances >= nrOfInstances }',
          loopCardinality: loopCharacteristics.loopCardinality?.body || '1',
          collection: loopCharacteristics.collection || '${coll_userList}',
          approveMethod,
          approveRatio,
        }
      } else {
        // 重置配置
        multiInstanceConfig.value = {
          isSequential: false,
          completionCondition: '${ nrOfCompletedInstances >= nrOfInstances }',
          loopCardinality: '1',
          collection: '${coll_userList}',
          approveMethod: ApproveMethodType.SEQUENTIAL_APPROVE,
          approveRatio: 100,
        }
      }
    },
    { immediate: true },
  )

  // 更新会签配置
  const updateMultiInstance = (config: MultiInstanceConfig) => {
    const { modeler, currentElement } = props
    if (!modeler || !currentElement) return

    const modeling = modeler.get('modeling') as Modeling
    const moddle = modeler.get('moddle') as Moddle

    // 如果是随机挑选一人审批，则移除多实例特性
    if (config.approveMethod === ApproveMethodType.RANDOM_SELECT_ONE_APPROVE) {
      modeling.updateProperties(currentElement, {
        loopCharacteristics: null,
      })
      return
    }

    // 根据审批方式设置相应的配置
    const isSequential = config.isSequential
    const completionConditionBody = config.completionCondition
    const loopCardinalityValue = config.loopCardinality

    // 创建或更新多实例特性
    const loopCharacteristics = moddle.create('bpmn:MultiInstanceLoopCharacteristics', {
      isSequential: isSequential,
      collection: config.collection,
    })

    // 设置完成条件
    const completionCondition = moddle.create('bpmn:FormalExpression', {
      body: completionConditionBody,
    })
    loopCharacteristics.completionCondition = completionCondition

    // 设置循环基数（会签人数）
    if (loopCardinalityValue) {
      const loopCardinality = moddle.create('bpmn:FormalExpression', {
        body: loopCardinalityValue,
      })
      loopCharacteristics.loopCardinality = loopCardinality
    }

    // 更新元素
    modeling.updateProperties(currentElement, {
      loopCharacteristics: loopCharacteristics,
    })
  }

  // 移除会签配置
  const removeMultiInstance = () => {
    const { modeler, currentElement } = props
    if (!modeler || !currentElement) return

    const modeling = modeler.get('modeling') as Modeling
    modeling.updateProperties(currentElement, {
      loopCharacteristics: null,
    })
  }

  // 处理会签配置变更
  const handleMultiInstanceChange = (value: boolean) => {
    isMultiInstance.value = value
    if (value) {
      // 开启会签，使用默认配置
      multiInstanceConfig.value = {
        isSequential: true, // 默认为顺序审批
        completionCondition: '${ nrOfCompletedInstances >= nrOfInstances }',
        loopCardinality: '1',
        collection: '${coll_userList}',
        approveMethod: ApproveMethodType.SEQUENTIAL_APPROVE, // 默认为顺序审批
        approveRatio: 100,
      }
      // 应用配置
      handleMultiInstanceUpdate()
    } else {
      // 关闭会签
      removeMultiInstance()
    }
  }

  // 处理会签配置更新
  const handleMultiInstanceUpdate = () => {
    if (isMultiInstance.value) {
      // 根据审批方式自动设置相关属性
      const config = { ...multiInstanceConfig.value }

      // 根据审批方式自动设置isSequential和completionCondition
      switch (config.approveMethod) {
        case ApproveMethodType.SEQUENTIAL_APPROVE:
          config.isSequential = true
          config.completionCondition = '${ nrOfCompletedInstances >= nrOfInstances }'
          break
        case ApproveMethodType.APPROVE_BY_RATIO:
          config.isSequential = false
          config.completionCondition =
            '${ nrOfCompletedInstances/nrOfInstances >= ' + config.approveRatio / 100 + '}'
          break
        case ApproveMethodType.ANY_APPROVE:
          config.isSequential = false
          config.completionCondition = '${ nrOfCompletedInstances >= 1 }'
          break
        case ApproveMethodType.RANDOM_SELECT_ONE_APPROVE:
          // 随机挑选一人审批不需要设置多实例属性
          break
      }

      // 更新到模型
      updateMultiInstance(config)
    }
  }

  // 处理审批方式变更
  const handleApproveMethodChange = (value: ApproveMethodType) => {
    multiInstanceConfig.value.approveMethod = value

    // 根据审批方式自动设置默认值
    switch (value) {
      case ApproveMethodType.SEQUENTIAL_APPROVE:
        // 顺序审批
        multiInstanceConfig.value.isSequential = true
        break
      case ApproveMethodType.APPROVE_BY_RATIO:
        // 按比例审批
        multiInstanceConfig.value.isSequential = false
        // 保持当前比例不变
        break
      case ApproveMethodType.ANY_APPROVE:
        // 或签（一人通过即可）
        multiInstanceConfig.value.isSequential = false
        break
      case ApproveMethodType.RANDOM_SELECT_ONE_APPROVE:
        // 随机一人审批
        break
    }

    handleMultiInstanceUpdate()
  }

  // 处理审批比例变更
  const handleApproveRatioChange = (value: number) => {
    multiInstanceConfig.value.approveRatio = value
    handleMultiInstanceUpdate()
  }

  return {
    showMultiInstance,
    isMultiInstance,
    multiInstanceConfig,
    multiInstanceVariables,
    handleMultiInstanceChange,
    handleMultiInstanceUpdate,
    handleApproveMethodChange,
    handleApproveRatioChange,
    APPROVE_METHODS,
  }
}
